<template>
    <div class="main_header">
        <div class="main_five_cube">五次方</div>
        <div class="main_navigation">
            <div v-for="(item,index) in menu" :key="index">
                <router-link :to="item.router">
                    <div class="main_navigation_item">{{ item.menu_name }}</div>
                </router-link>
            </div>
        </div>
        <div class="main_search">
            <a-input-search
                    v-model:value="requestParams.key"
                    placeholder="输入关键词..."
                    enter-button
                    :loading="isLoading"
                    size="large"
                    @keyup="handleKeyUp"
                    @search="search"
                    class="main_search_input"
            />
            <div class="main_search_ops">
                <div v-for="(item, index) in showOps"
                     :key="index"
                     v-show="isShow"
                     @click="search"
                     @mouseover="opsIndex = index"
                     :style='{"background-color": opsIndex===index ? "#EEE" : "#fff"}'
                >
                    <div class="main_search_ops_item">
                        <img class="main_search_ops_item_img" src="@/assets/img/answer/搜索.png" alt="搜索">
                        <div class="main_search_ops_item_option" @click="mouseClick(item)">{{ item }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="main_inform">
            <router-link to="/inform">
                <div class="main_inform_item">通知</div>
            </router-link>
        </div>
        <div v-if="cookie.get('userinfo')!=null">
            <a-dropdown>
                <img :src="userAvatar" class="main_avatar" alt="头像">
                <template #overlay>
                    <a-menu class="main_menu">
                        <a-menu-item class="item">
                            <router-link to="/my">
                                <a>个人中心</a>
                            </router-link>
                        </a-menu-item>
                        <a-menu-item class="item">
                            <router-link to="/inform">
                                <a>我的消息</a>
                            </router-link>
                        </a-menu-item>
                        <a-menu-item class="item item2">
                            <a @click="logout">退出登录</a>
                        </a-menu-item>
                    </a-menu>
                </template>
            </a-dropdown>
        </div>
        <div class="main_login_and_register" v-else>
            <div class="main_login">
                <div @click="router.push('/login')" class="main_login_item">
                    登录
                </div>
            </div>
            <div class="main_register">
                <div @click="router.push('/register')" class="main_register_item">
                    注册
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import {createVNode, onMounted, ref} from "vue";
// @ts-ignore
import cookie from 'js-cookie'
import router from "@/router";
import {Modal} from 'ant-design-vue';
import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
import {RequestParams} from "@/model/home/answer";
import {getSuggestion, searchArticle} from "@/api/home/article";
// @ts-ignore
import Publish from 'pubsub-js'
import lodash from "lodash";
import {useStore} from '@/store'

const menu = [
    {
        router: "/",
        menu_name: "文章",
    },
    {
        router: "/answer",
        menu_name: "问答",
    },
    {
        router: "/activity",
        menu_name: "活动",
    },
    {
        router: "/makeFriend",
        menu_name: "交友",
    },
    {
        router: "/tease",
        menu_name: "吐槽",
    },
    // {
    //     router: "/chatGPT",
    //     menu_name: "AI",
    // },
]

//自动补全显示的选项列表
const showOps = ref<string[]>([])
//当前索引
const opsIndex = ref<number>(-1)
//是否显示选项列表
const isShow = ref<boolean>(true)
//是否显示加载动画
const isLoading = ref<boolean>(false)

//全文检索所需的参数
const requestParams = ref<RequestParams>({
    key: '',
    page: 1,
    size: 10,
    sortBy: ''
})

//鼠标点击下拉框搜索
const mouseClick = (option: string) => {
    requestParams.value.key = option
    search()
}

//上下键选择搜索
//防抖 debounce
const handleKeyUp = lodash.debounce((e: any) => {
    if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 65 && e.keyCode <= 90) || e.keyCode === 8) {
        if (!requestParams.value.key) {
            // key没有值,不用搜索
            showOps.value = [];
            return;
        }
        getSuggestion(requestParams.value.key).then((res) => {
            showOps.value = res.data.data.list
        })
    } else if (e.keyCode === 38) {//上键
        if (opsIndex.value > 0) {
            opsIndex.value--;
            requestParams.value.key = showOps.value[opsIndex.value]
        } else {
            opsIndex.value = showOps.value.length - 1;
            requestParams.value.key = showOps.value[opsIndex.value]
        }
    } else if (e.keyCode === 40) {//下键
        opsIndex.value = (opsIndex.value + 1) % showOps.value.length;
        requestParams.value.key = showOps.value[opsIndex.value]
    } else if (e.keyCode === 13) {//回车键
        //按回车,则搜索
        search();
        showOps.value = []
    } else if (e.keyCode === 27) {//ESC键
        isShow.value = false
    }
}, 200)

//搜索
const search = () => {
    isLoading.value = true
    Publish.publish('receiveHeaderSearchKey', requestParams.value.key)
    router.push('/')
    // searchArticle(requestParams.value).then((res) => {
    //     res.data.data.pageResult.articles.map((item: any) => {
    //         item.title = item.title.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
    //         item.title = item.title.replaceAll("</em>", "</nobr>")
    //         item.labelTranslation = item.labelTranslation.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
    //         item.labelTranslation = item.labelTranslation.replaceAll("</em>", "</nobr>")
    //     })
    //     const store = useStore()
    //     store.setKey(requestParams.value.key)
    //     const msg = []
    //     msg.push(res.data.data.pageResult.articles)
    //     msg.push(requestParams.value.key)
    //     msg.push(res.data.data.pageResult.total)
    //     Publish.publish('searchArticleList', msg)
    //     router.push('/')
    //     isLoading.value = false
    //     showOps.value = []
    // })
}

//退出登录
const logout = () => {
    Modal.confirm({
        title: '你确定要退出吗?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确认',
        cancelText: '取消',
        onOk() {
            //移除cookie中的用户信息
            cookie.remove("token")
            cookie.remove("userinfo")
            //跳转首页
            router.push("/")
            //刷新页面
            // router.go(0)
            return new Promise((resolve, reject) => {
                setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
            }).catch(() => console.info('Oops errors!'));
        },
        onCancel() {
        },
    });
}

const userAvatar = ref('')

//从cookie中获取用户头像
const getAvatar = () => {
    if (cookie.get('userinfo') != null) {
        userAvatar.value = JSON.parse(cookie.get('userinfo')).avatar
    } else {
        userAvatar.value = ''
    }
}

onMounted(() => {
    getAvatar()
})
</script>

<style lang="less" scoped>
.main_header {
  display: flex;
  background-color: rgb(229, 229, 229);
  white-space: nowrap;

  .main_five_cube {
    font-style: italic;
    font-size: 30px;
    margin-left: 4%;
    font-weight: bold;
    line-height: 60px;
  }

  .main_navigation {
    margin-left: 2%;
    line-height: 60px;
    font-size: 20px;
    cursor: pointer;
    display: flex;

    .main_navigation_item {
      width: 5vw;
      height: 70px;
      text-align: center;
    }
  }

  .main_navigation_item:hover {
    background-image: linear-gradient(-225deg, #DFFFCD 0%, #90F9C4 48%, #39F3BB 100%);
  }

  .main_search {
    font-size: 18px;
    margin-left: 2%;
    margin-right: 20px;
    position: relative;
    width: 500px;

    .main_search_input {
      margin-top: 12px;
    }

    ::-webkit-input-placeholder {
      color: #03e9f4;
    }

    .main_search_ops {
      z-index: 99999;
      background-color: #fff;
      text-align: left;
      font-weight: bold;
      font-size: 15px;
      position: absolute;
      width: 100%;

      .main_search_ops_item {
        display: flex;
        cursor: pointer;

        .main_search_ops_item_img {
          width: 20px;
          height: 20px;
          margin: 10px;
        }

        .main_search_ops_item_option {
          padding-top: 7px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
    }
  }

  .main_inform {
    //margin-left: 2%;
    line-height: 60px;
    font-size: 20px;
    cursor: pointer;
    display: flex;
    margin-left: auto;

    .main_inform_item {
      width: 5vw;
      height: 70px;
      text-align: center;
    }
  }

  .main_inform_item:hover {
    background-image: linear-gradient(-225deg, #DFFFCD 0%, #90F9C4 48%, #39F3BB 100%);
  }

  .main_avatar {
    margin-left: 10%;
    line-height: 60px;
    cursor: pointer;
    width: 70px;
    height: 100%;
    border-radius: 50%;
    margin-right: 20px;

    &:deep(a-menu-item) {
      width: 500px !important;
    }
  }

  .main_login_and_register {
    display: flex;

    .main_login {
      margin-left: 2%;
      line-height: 60px;
      font-size: 20px;
      cursor: pointer;

      .main_login_item {
        width: 5vw;
        height: 70px;
        text-align: center;
      }
    }

    .main_login:hover {
      background-image: linear-gradient(-225deg, #DFFFCD 0%, #90F9C4 48%, #39F3BB 100%);
    }

    .main_register {
      margin-left: 2%;
      line-height: 60px;
      font-size: 20px;
      cursor: pointer;

      .main_register_item {
        width: 5vw;
        height: 70px;
        text-align: center;
      }
    }

    .main_register:hover {
      background-image: linear-gradient(-225deg, #DFFFCD 0%, #90F9C4 48%, #39F3BB 100%);
    }
  }
}

.main_menu {
  width: 150px;
  text-align: center;
  border-radius: 50px;

  :deep(.item) {
    padding: 10px;
  }

  :deep(.item:first-child) {
    border-top-left-radius: 50px;
    border-top-right-radius: 50px;
  }

  :deep(.item:last-child) {
    border-bottom-left-radius: 50px;
    border-bottom-right-radius: 50px;
  }
}

.router-link-active {
  color: red !important;
}

.router-link-exact-active {
  color: red !important;
}
</style>